package com.mamingchao.springcloud.eureka.service;

import com.mamingchao.springcloud.eureka.api.ProviderApi4;
import feign.FeignException;
import feign.hystrix.FallbackFactory;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.HttpServerErrorException;

/**
 * Created by mamingchao on 2020/9/10.
 */
@Component
public class HystrixFallbackFactory implements FallbackFactory<ProviderApi4>{

    @Override
    public ProviderApi4 create(Throwable throwable) {


        return new ProviderApi4() {

            @Override
            public String greeting() {
                return "greeting fallback factory method has been demoted";
            }

            /**
             * 如果传参数，这个地方不带 RequestParam
             * 会报错，错误信息
             * 【[ProviderApi2#hello(String)]: [{"timestamp":"2020-08-28T06:15:05.036+00:00","status":405,"error":"Method Not Allowed","message":"","path":"/serviceProvider/sayHello"}]】
             *
             * @param name
             * @return
             */
            @Override
            public String hello(@RequestParam("name") String name) {

                String errMsg = ToStringBuilder.reflectionToString(throwable);
                System.out.println(errMsg);
                if (throwable instanceof HttpServerErrorException.InternalServerError) {
                    System.out.println("Have coming into spring internal server error");
                } else if (throwable instanceof FeignException.InternalServerError){
                    System.out.println("Have coming into feign internal server error");
                }

                return throwable.getLocalizedMessage();
            }

            /**
             * @return
             */
            @Override
            public String ribbonReadTimeoutTest() {
                return "ribbonReadTimeoutTest fallback factory method has been demoted";
            }
        };
    }
}
